package com.jzo2o.trade.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.trade.config.WeChatPayProperties;
import com.jzo2o.trade.enums.TradingStateEnum;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IPayService;
import com.jzo2o.trade.service.ITradingService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务
 * 获取订单支付状态
 */
@Component
@Slf4j
public class CheckPayJob {

    @Resource
    private Config config;

    @Resource
    private WeChatPayProperties weChatPayProperties;

    @Resource
    private ITradingService tradingService;

    @Resource
    private IPayService payService;

    @XxlJob("CheckPayResult")
    public void queryResult() {
        // 构建service
        NativePayService service = new NativePayService.Builder().config(config).build();
        // 查询在支付中，且五分钟前的交易单
        LambdaQueryWrapper<Trading> tradingLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tradingLambdaQueryWrapper.eq(Trading::getTradingState, TradingStateEnum.FKZ.getCode())
                .lt(Trading::getCreateTime, LocalDateTime.now().minusMinutes(5L));
        List<Trading> tradingList = tradingService.list(tradingLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(tradingList)) {
            log.info("没有符合条件的交易单");
            return;
        }

        //查询所有符合条件的交易单
        try {
            for (Trading trading : tradingList) {
                QueryOrderByOutTradeNoRequest orderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
                orderByOutTradeNoRequest.setMchid(weChatPayProperties.getMerchantId());
                orderByOutTradeNoRequest.setOutTradeNo(trading.getTradingOrderNo());
                // 如果是微信支付
                if (PayChannelEnum.WECHAT_PAY.getValue().equals(trading.getTradingChannel())){
                    Transaction result = service.queryOrderByOutTradeNo(orderByOutTradeNoRequest);
                    log.info("查询结果：{}", result);
                    payService.deal(result, trading);
                }
            }

        } catch (ServiceException e) {
            // API返回失败, 例如ORDER_NOT_EXISTS
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());

        }
    }
}

